package com.itheima.controller;

import com.itheima.pojo.Result;
import com.itheima.utils.AliOSSUtils;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

@RestController
@Slf4j
@RequestMapping("/upload")
public class UploadController {

  /*  @PostMapping
    public Result upload(MultipartFile image) throws IOException {
        //日志
        log.info("文件上传：{}", image);
        //获取文件名
        String str = image.getOriginalFilename();
        //截取后缀
        String last = str.substring(str.lastIndexOf("."));
        //生成唯一字符串名，拼接后缀，形成新的文件名
        String newStr = UUID.randomUUID().toString() + last;
        //将文件保存到指定位置
        image.transferTo(new File("D:/" + newStr));

        return Result.success();
    }*/

    @Autowired
    private AliOSSUtils aliOSSUtils;

    @PostMapping
    public Result upload(MultipartFile image) throws IOException {
        //日志
        log.info("文件上传：{}", image);
        //调用文件上传工具
        String url = aliOSSUtils.upload(image);
        //将图片返回给前端预览
        return Result.success(url);
    }
}
